#include <zenilib.h>
#include <time.h>
#include "Civilian.h"
#include "Person.h"

using namespace Zeni;
using namespace std;

Civilian::Civilian(Vector2 pos)
{
	playertype = CIVILIAN;
	body = new Person(pos);
	brain = NULL;
	controlsPerson = true;
	InitializeControls(pos);
	this->jumpVelocity = -400.0f;
	this->walkVelocity = 200.0f;
}

Civilian::Civilian(SpriteObject* body_)
{
	playertype = CIVILIAN;
	body = body_;
	brain = NULL;
	InitializeControls(body_->getPos());
	controlsPerson = true;
	this->jumpVelocity = -400.0f;
	this->walkVelocity = 200.0f;
}

void Civilian::determineAction(std::vector<Platform*> &platforms,
															 std::vector<Player*> &npcs,
															 Player* player,
															 float timestep)
{
	timeElapsedPerformingAction += timestep;

	playerCanSee = (player->distanceFrom(this) < 1000);
	// Check if the civilian hits a wall
	if((controls.left || controls.right) && 
		 this->previousPosition == this->getPos())
	{
		controls.jump = true;
	}

	int xdist = player->getPos().x-this->getPos().x;
	int ydist = player->getPos().y-this->getPos().y;
	int dist = sqrt(1.0f*(xdist*xdist + ydist*ydist));
	if(dist > 200.0f || player->controlsPerson)
	{
		if(timeElapsedPerformingAction > timeToPerformAction)
		{
			timeElapsedPerformingAction = 0.0f;
			controls.down = controls.fire = 
				controls.left = controls.right = controls.up = false;

			// perform random action
			timeToPerformAction = .2f * (rand() % 5 + 1);

			if(dist < 250 && xdist > 0 && !player->controlsPerson)
				controls.left = true;
			else if(dist < 250 && !player->controlsPerson)
				controls.right = true;
			else 
			{
				int action = rand() % 7;
				switch(action) {
					case 0:
					case 1:
						break;
					case 2:
					case 3:
						controls.left = true;
						break;
					case 4:
					case 5:
						controls.right = true;
						break;
					case 6:
						controls.jump = true;
						break;
					default:
						break;
				}
			}
		}
	}
	else 
	{
		// run away from brain slug
		controls.down = controls.fire = 
			controls.left = controls.right = controls.up = false;
		timeElapsedPerformingAction = 0.0f;
		timeToPerformAction = 0.0f;
		if(xdist > 0)
			controls.left = true;
		else
			controls.right = true;
	}

	//controls.down = controls.fire = controls.up = false;
	//if(player->getPos().x < getPos().x)
	//{
	//	controls.left = true;
	//	controls.right = false;
	//}
	//else
	//{
	//	controls.right = true;
	//	controls.left = false;
	//}

	//if(player->getPos().y < getPos().y)
	//	controls.jump = true;
	//else
	//	controls.jump = false;
}
